<template>
	<view class="my-protocol" ref="uv-back-top">
		<headers @custom-event="customevent" :opacity='0' :return_url="return_url"></headers>
		<uv-navbar v-if="!screen" title="支付中" @leftClick="routed()" rightText="" :placeholder="true"></uv-navbar>
		<web-view :src="src"></web-view>
	</view>
</template>

<script>
	import headers from '@/components/header/header.vue';
	import config from '@/common/config.js';
	export default {
		components: {
			// 注册组件
			headers
		},
		data() {
			return {
				src: '',
				return_url: ''
			};
		},
		onLoad(option) {
			// console.log(option);
			// return;
			var url = this.getQueryParams(option.url);
			this.src = option.url;
			this.return_url = url.return_url.split('#')[1] ? url.return_url.split('#')[1] : '';
		},
		onUnload() {
			this.canLeave = true; // 页面卸载时清理状态
		},
		beforeRouteLeave(to, from, next) {
			if (this.isPaying && !this.canLeave) { // 提示用户确认离开
				this.showLeaveConfirm(next);
			} else {
				next();
			}
		},
		methods: {
			async handlePayment() {
				// 防重复提交
				if (this.isSubmitting) {
					return;
				}

				this.isSubmitting = true;
				this.isPaying = true;

				try {
					// 设置超时控制
					const timeoutPromise = new Promise((_, reject) => {
						setTimeout(() => reject(new Error('支付超时')), 10000);
					});

					const paymentPromise = this.createPayment();

					// 竞速处理
					await Promise.race([paymentPromise, timeoutPromise]);

				} catch (error) {
					console.error('支付错误:', error);
					uni.showToast({
						title: '支付失败，请重试',
						icon: 'none'
					});
				} finally {
					this.isSubmitting = false;
					this.isPaying = false;
				}
			},
			showLeaveConfirm(next) {
				uni.showModal({
					title: '离开确认',
					content: '支付尚未完成，确定要离开吗？',
					success: (res) => {
						if (res.confirm) {
							this.canLeave = true;
							next();
						} else {
							next(false);
						}
					}
				});
			},
			getQueryParams(url) {
				// 使用URLSearchParams解析查询字符串
				const params = new URLSearchParams(url.split('?')[1]);
				let result = {};
				// 将所有参数添加到结果对象中
				for (const [key, value] of params) {
					result[key] = value;
				}
				return result;
			},
			routed(url) {
				uni.$uv.route({
					type: 'reLaunch',
					url: config.rechargeUrl,
					intercept(params, next) {
						console.log(params, next)
						uni.showLoading({
							title: '等待中...'
						})
						// 模拟处理等待
						setTimeout(() => {
							uni.hideLoading();
							next(true);
						}, 1000)
					}
				})
			}
		}
	};
</script>